﻿using FluorineFx.IO;
using FluorineFx.Messaging.Messages;
using SettlersAuto.Data.AmfTypes;
using SettlersAuto.Data.Entities;
using System.IO;

namespace SettlersAuto.Data
{
    public static class DataImport
    {
        static DataImport()
        {
            Configuration.RegisterCustomTypes();
        }

        public static void ProcessServerResponse(byte[] bytes)
        {
            using (var stream = new MemoryStream(bytes))
            {
                var deserializer = new AMFDeserializer(stream);
                var message = deserializer.ReadAMFMessage();

                foreach (var body in message.Bodies)
                {
                    var acknowledgeMessage = body.Content as AcknowledgeMessage;
                    if (acknowledgeMessage != null)
                    {
                        var serverResponse = acknowledgeMessage.body as ServerResponse;
                        if (serverResponse != null)
                        {
                            var tradeWindowResult = serverResponse.data.data as TradeWindowResultVO;
                            if (tradeWindowResult != null)
                            {
                                ProcessTradeWindowResult(bytes, tradeWindowResult);
                            }

                            var zone = serverResponse.data.data as ZoneVO;
                            if (zone != null)
                            {
                                ProcessZone(zone);
                            }
                        }
                    }
                }

                foreach (var failedBody in deserializer.FailedAMFBodies)
                {
                    var errorMessage = failedBody.Content as ErrorMessage;
                    if (errorMessage != null)
                    {
                        System.Diagnostics.Debug.WriteLine("AMFDeserializer.ReadAMFMessage.ErrorMessage: " + errorMessage.faultString);
                    }
                }
            }
        }

        private static void ProcessZone(ZoneVO zone)
        {
            
        }

        private static void ProcessTradeWindowResult(byte[] bytes, TradeWindowResultVO tradeWindowResult)
        {
            using (var db = new SettlersAutoDb())
            {
                db.BeginTransaction();
                var responseHandler = new ServerResponseHandler(db);
                var sessionId = responseHandler.InsertTradeSession(bytes);
                responseHandler.ProcessTradeWindowResult(sessionId, tradeWindowResult);
                db.CommitTransaction();
            }
        }
    }
}
